﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using EntityFramework.Extensions;
using Webcar.Utils;
namespace Webcar.Controllers
{
    public partial class AccountController
	{
        public ActionResult List()
        {
            return View();
        }
        public ActionResult ListPartialView()
        {
            return PartialView();
        }
        public ActionResult UserPermissionSave(string id)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑系统操作员);
            //保存具体权限
            string all_permissions = Request.Form["selectPermissions"];
            string[] permission_list = all_permissions.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
            var revoke_list = Request.Form["selectRevokePermissions"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            using (var DB = new WebcarContext())
            {
                DB.sys_user_purview.Delete(a => a.userid == id);
                foreach (var permission in permission_list.Union(revoke_list).Distinct())
                {
                    sys_user_purview purview = new sys_user_purview();
                    purview.userid = id;
                    purview.purview_id = permission;
                    if (Array.IndexOf(revoke_list, permission) >= 0)
                    {
                        purview.purview_type = "revoke";
                    }
                    else
                    {
                        purview.purview_type = "grant";
                    }
                    DB.sys_user_purview.Add(purview);
                }
                //保存权限组
                string all_groups = Request.Form["selectGroupList"];
                string[] group_list = all_groups.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                DB.GROUP_MAN.Delete(a => a.OPER_CODE == id);
                foreach (var group in group_list)
                {
                    GROUP_MAN user_group = new GROUP_MAN();
                    user_group.OPER_CODE = id;
                    user_group.GROUP_CODE = group;
                    DB.GROUP_MAN.Add(user_group);
                }
                string all_depts = Request.Form["selectDept"];
                string[] deptList = all_depts.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                DB.BS_MAN_DEPT.Delete(a => a.MAN_CODE == id);
                foreach (var dept in deptList)
                {
                    BS_MAN_DEPT man_dept = new BS_MAN_DEPT();
                    man_dept.DEPT_CODE = dept;
                    man_dept.MAN_CODE = id;
                    DB.BS_MAN_DEPT.Add(man_dept);
                }
                DB.SaveChanges();
            }
            return RedirectToAction("List");
        }

        public ActionResult UserPermissions(string id)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑系统操作员);
            //处理该用户明细权限数据
            var query = (from p in WebcarDataProvider.DB.v_user_purview
                         select p).ToList();

            var user = WebcarDataProvider.DB.v_all_users.Find(id);
            var result = (from p2 in PermissionManager.AllPermissions
                          join p in query.Where(a => a.userid == id)
                          on p2.PermissionId equals p.purview_id
                          into pp
                          from bb in pp.DefaultIfEmpty()
                          select new
                          {
                              PermissionId = p2.PermissionId,
                              Name = p2.Name,
                              Module = p2.Module,
                              PurviewType=bb!=null?bb.purview_type:"grant",
                              PermissionType = p2.PermissionType,
                              Selected = bb == null ? false : true,
                              Source=bb!=null?bb.psource:1
                          }).ToList();
            ViewBag.SelectedRowIds = result.Where(a => a.Selected).Select(a => a.PermissionId).Join(";");
            if (user != null)
            {
                ViewBag.UserName = user.name;
            }
            //处理该用户权限组数据
            var group_query = from p in WebcarDataProvider.DB.USER_GROUP
                              join p2 in WebcarDataProvider.DB.GROUP_MAN.Where(a => a.OPER_CODE == id)
                              on p.GROUP_CODE equals p2.GROUP_CODE
                              into pp
                              from bb in pp.DefaultIfEmpty()
                              select new { 
                                  GROUP_CODE=p.GROUP_CODE,
                                  GROUP_NOTE = p.GROUP_NOTE,
                                  NOTE=p.NOTE,
                                  IS_DEFAULT=p.IS_DEFAULT,
                                  Selected = bb == null ? false : true
                              };
            var grouplist = group_query.ToList();
            ViewBag.GroupList = grouplist;
            ViewBag.SelectedGroupIds = grouplist.Where(a => a.Selected).Select(a => a.GROUP_CODE).Join(";");
            //处理该用户已被拒绝授予的权限
            var revoke_list = (from p2 in PermissionManager.AllPermissions
                          join p in query.Where(a => a.userid == id&&a.purview_type=="revoke")
                          on p2.PermissionId equals p.purview_id
                          into pp
                          from bb in pp.DefaultIfEmpty()
                          select new
                          {
                              PermissionId = p2.PermissionId,
                              Name = p2.Name,
                              Module = p2.Module,
                              PermissionType = p2.PermissionType,
                              Selected = bb == null ? false : true,
                              Source=bb!=null?bb.psource:1
                          }).ToList();
            ViewBag.RevokeList = revoke_list;
            ViewBag.RevokeSelectedRowIds = revoke_list.Where(a => a.Selected).Select(a => a.PermissionId).Join(";");
            return View(model: result);
        }
        [HttpGet]
        public ActionResult Edit(string id)
        {
            WORK_MAN model = null;
            if (id.IsNotNull())
            {
                model = WebcarDataProvider.DB.WORK_MAN.Find(id);
            }
            if (model == null)
            {
                model = new WORK_MAN();
                
            }

            return View(model: model);
        }
        [HttpPost]
        public ActionResult Edit(WORK_MAN model)
        {
            string edit_model = Request.Form["edit_model"];
            if (model.OPER_CODE.IsNull() || model.OPER_NAME.IsNull())
            {
                ViewBag.ErrorMessage = "请输入用户名和姓名。";
                return View(model);
            }
            if (model.DEPT.IsNull())
            {
                ViewBag.ErrorMessage = "请选择用户单位。";
                return View(model);
            }
            if (model.IsAdmin && CurrentUser.IsSuperUser == false)
            {
                ViewBag.ErrorMessage = "你不能添加系统管理员。";
                return View(model);
            }
            if (model.PWD.IsNull())
            {
                model.PWD = "111".MD5Hash();
                model.IS_ENABLE = "T";
            }


            using (var DB = new WebcarContext())
            {
                if (edit_model == "add")
                {
                    var find = DB.v_all_users.Find(model.OPER_CODE);
                    if (find != null)
                    {
                        if (find.account == model.OPER_CODE || find.cn == model.OPER_CODE)
                        {
                            ViewBag.ErrorMessage = "该用户代码已经存在。";
                            return View(model);
                        }
                    }
                }
                WORK_MAN exists = DB.WORK_MAN.Find(model.OPER_CODE);
                if (exists == null)
                {
                    DB.WORK_MAN.Add(model);
                }
                else
                {
                    model.CopyPropertyTo(exists);
                }
                DB.SaveChanges();
            }

            return RedirectToAction("List");
        }
        public ActionResult Delete(string id)
        {
            using (var DB = new WebcarContext())
            {
                DB.WORK_MAN.Delete(a => a.OPER_CODE == id);
                DB.SaveChanges();
            }
            return RedirectToAction("List");
        }
        public ActionResult Reset(string id)
        {
            using (var DB = new WebcarContext())
            {
                var user = DB.WORK_MAN.Find(id);
                if (user != null)
                {
                    user.PWD = "111".MD5Hash();
                }
                DB.SaveChanges();
            }
            return Success("List","Account");
        }

	}
}